import { defineStore } from 'pinia'
import { computed, ref, watch } from 'vue'

export const useCartHooks = defineStore('cart', () => {
  /**
   * selectSKU
   * count
   * state
   *
   */
  const cartList = ref([])

  const allState = computed(() => cartList.value.every((v) => v.state))
  const allPrice = computed(() => {
    return cartList.value.reduce((p, n) => {
      return n.state ? p + n.count * n.price : p
    }, 0)
  })
  watch(cartList.value, () => {
    console.log('购物车数据：', cartList.value)
  })

  const addCart = (item) => {
    const v = cartList.value.find((v) => {
      return v.id === item.id && JSON.stringify(v.selectSku) === JSON.stringify(item.selectSku)
    })
    // 存在
    if (v) {
      v.count++
      return
    }
    // 不存在
    cartList.value.push(item)
  }
  const changeAllState = () => {
    const flag = !allState.value
    cartList.value.forEach((v) => {
      v.state = flag
    })
  }

  return { cartList, addCart, allState, changeAllState, allPrice }
})
